package ua.pp.parkee.t5;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Pavlo_Klivak on 8/19/2014.
 */
public class Bank {

    private List<Account> accounts = new ArrayList<>();

    public Account getAccount(int number) {
        return accounts.get(number);
    }

    public void addAccount(Account account) {
        accounts.add(account);
    }

    public void transfer(Account from, Account to, int amount) {

        if(from == to) return;
        if(amount <= 0) return;

        while (true) {
            if(from.getLock().tryLock()) {
                try {
                    if (to.getLock().tryLock()) {
                        try {
                            if (from.getAmount() >= amount) {
                                from.withdraw(amount);
                                to.deposit(amount);
                                return;
                            } else {
                                throw new InsufficientAmountException();
                            }
                        } finally {
                            to.getLock().unlock();
                        }
                    }
                } finally {
                    from.getLock().unlock();
                }
            }
        }
    }
}
